package cn.lblbc.webbrowser.utils

import android.content.Context
import android.widget.ImageView
import androidx.core.content.ContextCompat
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import cn.lblbc.webbrowser.R
import java.io.File

/**
 * 背景图片管理器
 * 用于管理首页背景图片的设置和应用
 */
class BackgroundImageManager(private val context: Context) {
    
    companion object {
        private const val PREFS_NAME = "home_settings"
        private const val KEY_BACKGROUND_IMAGE = "background_image"
        private const val KEY_BACKGROUND_ENABLED = "background_image_enabled"
    }
    
    private val prefs = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
    
    /**
     * 获取当前设置的背景图片路径
     */
    fun getCurrentBackgroundImage(): String? {
        return prefs.getString(KEY_BACKGROUND_IMAGE, null)
    }
    
    /**
     * 设置背景图片
     * @param imagePath 图片路径，null表示使用默认背景
     */
    fun setBackgroundImage(imagePath: String?) {
        prefs.edit().putString(KEY_BACKGROUND_IMAGE, imagePath).apply()
    }
    
    /**
     * 设置背景图片启用状态
     * @param enabled 是否启用背景图片
     */
    fun setBackgroundImageEnabled(enabled: Boolean) {
        prefs.edit().putBoolean(KEY_BACKGROUND_ENABLED, enabled).apply()
    }
    
    /**
     * 获取背景图片启用状态
     * @return 是否启用背景图片
     */
    fun isBackgroundImageEnabled(): Boolean {
        return prefs.getBoolean(KEY_BACKGROUND_ENABLED, true)
    }
    
    /**
     * 应用背景图片到ImageView
     * @param imageView 要设置背景的ImageView
     */
    fun applyBackgroundToImageView(imageView: ImageView) {
        if (!isBackgroundImageEnabled()) {
            // 背景图片被禁用，清除ImageView的背景
            android.util.Log.d("BackgroundImageManager", "Background image is disabled, clearing background")
            imageView.setImageDrawable(null)
            return
        }
        
        val backgroundPath = getCurrentBackgroundImage()
        android.util.Log.d("BackgroundImageManager", "Applying background: $backgroundPath")
        
        when {
            backgroundPath == null -> {
                // 使用默认背景
                android.util.Log.d("BackgroundImageManager", "Using default background")
                Glide.with(context)
                    .load(R.drawable.bg)
                    .centerCrop()
                    .diskCacheStrategy(DiskCacheStrategy.RESOURCE)
                    .into(imageView)
            }
            backgroundPath.startsWith("img") -> {
                // 使用内置drawable资源
                android.util.Log.d("BackgroundImageManager", "Using bundled image: $backgroundPath")
                try {
                    val resourceId = context.resources.getIdentifier(
                        backgroundPath, 
                        "drawable", 
                        context.packageName
                    )
                    android.util.Log.d("BackgroundImageManager", "Resource ID for $backgroundPath: $resourceId")
                    
                    if (resourceId != 0) {
                        Glide.with(context)
                            .load(resourceId)
                            .centerCrop()
                            .diskCacheStrategy(DiskCacheStrategy.RESOURCE)
                            .into(imageView)
                        android.util.Log.d("BackgroundImageManager", "Loaded bundled image with Glide")
                    } else {
                        // 资源不存在，使用默认背景
                        android.util.Log.e("BackgroundImageManager", "Resource not found: $backgroundPath")
                        Glide.with(context)
                            .load(R.drawable.bg)
                            .centerCrop()
                            .diskCacheStrategy(DiskCacheStrategy.RESOURCE)
                            .into(imageView)
                    }
                } catch (e: Exception) {
                    android.util.Log.e("BackgroundImageManager", "Error loading bundled image: $backgroundPath", e)
                    e.printStackTrace()
                    Glide.with(context)
                        .load(R.drawable.bg)
                        .centerCrop()
                        .diskCacheStrategy(DiskCacheStrategy.RESOURCE)
                        .into(imageView)
                }
            }
            else -> {
                // 使用外部文件
                android.util.Log.d("BackgroundImageManager", "Using external file: $backgroundPath")
                val file = File(backgroundPath)
                if (file.exists() && file.isFile) {
                    Glide.with(context)
                        .load(file)
                        .centerCrop()
                        .diskCacheStrategy(DiskCacheStrategy.DATA)
                        .into(imageView)
                    android.util.Log.d("BackgroundImageManager", "Loaded external file with Glide")
                } else {
                    // 文件不存在，使用默认背景
                    android.util.Log.e("BackgroundImageManager", "External file not found: $backgroundPath")
                    Glide.with(context)
                        .load(R.drawable.bg)
                        .centerCrop()
                        .diskCacheStrategy(DiskCacheStrategy.RESOURCE)
                        .into(imageView)
                    // 清除无效的设置
                    setBackgroundImage(null)
                }
            }
        }
    }
    
    /**
     * 获取背景图片的显示名称
     */
    fun getBackgroundImageDisplayName(): String {
        val backgroundPath = getCurrentBackgroundImage()
        return when {
            backgroundPath == null -> "默认背景"
            backgroundPath.startsWith("img") -> "内置图片: ${backgroundPath.removePrefix("img")}"
            else -> {
                val file = File(backgroundPath)
                if (file.exists()) {
                    when {
                        file.parent?.contains("WebImages") == true -> "收集图片: ${file.name}"
                        file.parent?.contains("Backgrounds") == true -> "相册图片: ${file.name}"
                        else -> "自定义图片: ${file.name}"
                    }
                } else {
                    "默认背景"
                }
            }
        }
    }
    
    /**
     * 获取所有可用的内置背景图片
     */
    fun getBundledImages(): List<String> {
        val bundledImages = mutableListOf<String>()
        try {
            val pkg = context.packageName
            val drawableClass = Class.forName("$pkg.R\$drawable")
            val fields = drawableClass.declaredFields
            
            for (field in fields) {
                val name = field.name
                if (name.startsWith("img")) {
                    bundledImages.add(name)
                    android.util.Log.d("BackgroundImageManager", "Found bundled image: $name")
                }
            }
            android.util.Log.d("BackgroundImageManager", "Total bundled images found: ${bundledImages.size}")
        } catch (e: Exception) {
            android.util.Log.e("BackgroundImageManager", "Error getting bundled images", e)
            e.printStackTrace()
        }
        return bundledImages.sorted()
    }
}